package com.sunshine.wrongquestionset.activity.main

import android.content.Context
import android.content.Intent
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textview.MaterialTextView
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.AddQuestionActivity
import com.sunshine.wrongquestionset.activity.question.QuestionActivity
import com.sunshine.wrongquestionset.activity.question_set.QuestionSetActivity
import com.sunshine.wrongquestionset.callback.QuestionOptionsListener
import com.sunshine.wrongquestionset.utils.AnalyzerUtils
import com.sunshine.wrongquestionset.view.HasEmptyRecyclerAdapter
import com.sunshine.wrongquestionset.view.QuestionContentBottomSheetDialog
import es.dmoral.toasty.Toasty
import java.text.DecimalFormat

/**
 * @author sunshine
 * @date 2021/4/11
 */
class SearchRecyclerAdapter(
    private val owner: LifecycleOwner,
    private val viewModel: MainViewModel,
    private val activity: AppCompatActivity
) : HasEmptyRecyclerAdapter<SearchRecyclerAdapter.ViewHolder>(null) {

    private var list: ArrayList<SearchBean>? = null
    private lateinit var context: Context
    private var backgroundList: ArrayList<Int> = ArrayList()
    //百分数保留2位
    private val decimalFormat = DecimalFormat("0.##%")

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val root: MaterialCardView = itemView.findViewById(R.id.root_search)
        val viewColor: View = itemView.findViewById(R.id.view_color)

        val mName: MaterialTextView = itemView.findViewById(R.id.name)
        val mDescription: MaterialTextView = itemView.findViewById(R.id.description)

        val mType: MaterialTextView = itemView.findViewById(R.id.type)
        val imageType: ImageView = itemView.findViewById(R.id.imageView_search_type)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        this.context = parent.context
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_search, parent, false))
    }

    override fun getItemCount(): Int {
        return list?.size?:0
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.mDescription.text = list!![position].description
        when (list!![position].type) {
            1 -> {
                holder.mType.text = "科目"
                holder.mName.text = list!![position].name
                holder.imageType.setImageResource(R.drawable.ic_outline_architecture_24)
                holder.viewColor.setBackgroundColor(context.getColor(R.color.item_background_solid_1))
                holder.root.setOnClickListener {
                    val intent = Intent(context, QuestionSetActivity::class.java)
                    intent.putExtra("subjectId", list!![position].id)
                    context.startActivity(intent)
                }
            }
            2 -> {
                holder.mType.text = "错题本"
                holder.mName.text = list!![position].name
                holder.imageType.setImageResource(R.drawable.ic_outline_assignment_24)
                holder.viewColor.setBackgroundColor(context.getColor(R.color.item_background_solid_3))
                holder.root.setOnClickListener {
                    val intent = Intent(context, QuestionActivity::class.java)
                    intent.putExtra("type", QuestionActivity.TYPE_QUESTION_SET)
                    intent.putExtra("subjectId", list!![position].param as Int)
                    intent.putExtra("setId", list!![position].id)
                    context.startActivity(intent)
                }
            }
            3 -> {
                val titlePath = list!![position].name
                holder.mName.text =
                    if (titlePath.contains(Regex("!\\[.*]\\(.*\\)"))) "内含图片，请点击查看"
                    else titlePath

                holder.mType.text = "题目"
                holder.imageType.setImageResource(R.drawable.ic_outline_edit_24)
                holder.viewColor.setBackgroundColor(context.getColor(R.color.item_background_solid_5))
                holder.root.setOnClickListener {
                    viewModel.getQuestionById(list!![position].id).observe(owner, Observer {questionEntity ->
                        if (it != null) {
                            //练习记录熟悉程度变化折线图
                            viewModel.getQuestionInfoByQuestionId(list!![position].id).observe(owner, Observer { questionInfoList ->
                                viewModel.getWrongQuestionBeanByQuestionId(list!![position].id).observe(owner, Observer { wrongQuestionBeanList ->
                                    val questionFamiliarityBean =
                                        AnalyzerUtils.analyzerQuestionFamiliarity(questionInfoList, 10)
                                    viewModel.getQuestionType(questionEntity!!.typeId)
                                        .observe(owner, Observer { type ->
                                            QuestionContentBottomSheetDialog.show(
                                                activity,
                                                questionEntity.titlePath,
                                                questionEntity.answerPath,
                                                "题目类型：$type 熟悉程度：${decimalFormat.format(questionEntity.familiarity)}",
                                                questionFamiliarityBean,
                                                wrongQuestionBeanList,
                                                object : QuestionOptionsListener {
                                                    override fun onDelete() {
                                                        //删除题目
                                                        val builder =
                                                            MaterialAlertDialogBuilder(context)
                                                        builder.apply {
                                                            setTitle(context.getString(R.string.warning_title))
                                                            setMessage(Html.fromHtml(context.getString(R.string.delete_question_warning)))
                                                            setPositiveButton("我再想想") { _, _ -> }
                                                            setNegativeButton("删除") { _, _ ->
                                                                viewModel.deleteQuestion(questionEntity)
                                                                Toasty.success(
                                                                    context,
                                                                    context.getString(R.string.delete_success)
                                                                ).show()
                                                            }
                                                        }
                                                        builder.create().show()
                                                    }

                                                    override fun onEdit() {
                                                        AddQuestionActivity.editQuestionEntity =
                                                            questionEntity
                                                        val intent = Intent(
                                                            context,
                                                            AddQuestionActivity::class.java
                                                        )
                                                        intent.putExtra(
                                                            "type",
                                                            AddQuestionActivity.TYPE_EDIT
                                                        )
                                                        context.startActivity(intent)
                                                    }

                                                }
                                            )
                                        })
                                })

                            })
                        }
                    })
                }
            }
        }
    }

    fun setFilter(list: ArrayList<SearchBean>) {
        this.list = list
        notifyDataSetChanged(list)
    }

    init {
        backgroundList.apply {
            add(R.drawable.ripple_item_bg_7)
            add(R.drawable.ripple_item_bg_8)
            add(R.drawable.ripple_item_bg_9)
        }
    }
}